package com.cg.utils;

import com.cg.common.KeyCommon;
import com.cg.dto.LoginPatientUserDto;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName TokenUtils
 * @Description TODO
 * @Author CG
 * @Date 2024/1/4 21:27
 **/
public class TokenUtils {

    /**
     * 创建token
     */
    public static String createToken(LoginPatientUserDto loginPatientUserDto){
        //token格式
        //token:PC-PHONE[加密]-USERID-CREATIONDATE-RONDEM[6 位]
        //获取手机号
        String phone = loginPatientUserDto.getPhone();
        //手机号加盐加密
        //加密
        phone = MD5Utils.MD5(phone);
        //拼接
        StringBuilder stringBuilder = new StringBuilder(KeyCommon.USER_TOKEN_KEY);
        stringBuilder.append(phone);
        stringBuilder.append("-");
        stringBuilder.append(loginPatientUserDto.getPatientUserId());
        stringBuilder.append("-");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        //获取当前时间
        Date date = new Date();
        stringBuilder.append(simpleDateFormat.format(date));
        stringBuilder.append("-");
        //生成6位的随机数
        //现获取UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String substring = uuid.substring(uuid.length() - 6);
        stringBuilder.append(substring);
        return stringBuilder.toString();
    }


    /**
     * 根据token获取userId
     */
    public static Integer getUserIdByToken(String token){
        String[] split = token.split("-");
        String userIdStr = split[2];
        return Integer.parseInt(userIdStr);
    }


}
